

package com.dog.basics.sys.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dog.basics.bean.dto.admin.sys.AdminSysMenuAddDto;
import com.dog.basics.bean.dto.admin.sys.AdminSysMenuEditDto;
import com.dog.basics.bean.model.sys.SysMenu;
import com.dog.basics.bean.vo.admin.sys.MenuTree;
import com.dog.basics.bean.model.sys.SysUserRole;
import com.dog.basics.bean.vo.admin.sys.AdminMenuVO;
import com.dog.basics.common.annotation.SysLog;
import com.dog.basics.common.util.R;
import com.dog.basics.security.util.SecurityUtils;
import com.dog.basics.service.sys.SysMenuService;
import com.dog.basics.service.sys.SysUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import ma.glasnost.orika.MapperFacade;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author guonh
 * @date 2017/10/31
 */
@RestController
@AllArgsConstructor
@RequestMapping("/admin/menu")
@Api(value = "菜单管理模块", tags = "菜单管理模块")
public class SysMenuController {

    private final SysMenuService sysMenuService;
    private final SysUserRoleService sysUserRoleService;
    private final MapperFacade mapperFacade;
    /**
     * 返回当前用户的树形菜单集合
     *
     * @param type     类型
     * @param parentId 父节点ID
     * @return 当前用户的树形菜单
     */
    @GetMapping
    @ApiOperation(value = "返回当前用户的树形菜单集合", notes = "sys_menu_list")
    @PreAuthorize("@pms.hasPermission('sys_menu_list')")
    public R<List<MenuTree>> getUserMenu(String type, Long parentId) {
        //查询当前用户的角色
        List<SysUserRole> list = sysUserRoleService.list(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, SecurityUtils.getSysUser().getUserId()));
        Validator.validateTrue(CollUtil.isNotEmpty(list), "该用户未分配角色");
        // 获取符合条件的菜单
        Set<AdminMenuVO> all = new HashSet<>();
        if(Validator.equal(SecurityUtils.getSysUser().getUserId(),1L)){
            List<SysMenu> oldList=sysMenuService.list(Wrappers.<SysMenu>lambdaQuery());
            List<AdminMenuVO> newList= mapperFacade.mapAsList(oldList,AdminMenuVO.class);

            all.addAll(newList);
        }else{
            all.addAll(sysMenuService.findMenuByRoleId(list.get(0).getRoleId()));
        }
        //SecurityUtils.getRoles().forEach(roleId -> all.addAll(sysMenuService.findMenuByRoleId(roleId)));
        return R.ok(sysMenuService.filterMenu(all, type, parentId));
    }

    /**
     * 返回树形菜单集合
     *
     * @param lazy     是否是懒加载
     * @param parentId 父节点ID
     * @return 树形菜单
     */
    @GetMapping(value = "/tree")
    @ApiOperation(value = "返回树形菜单集合", notes = "sys_menu_tree")
    @PreAuthorize("@pms.hasPermission('sys_menu_tree')")
    public R<List<MenuTree>> getTree(boolean lazy, Long parentId) {
        return R.ok(sysMenuService.treeMenu(lazy, parentId));
    }

    /**
     * 返回角色的菜单集合
     *
     * @param roleId 角色ID
     * @return 属性集合
     */
    @GetMapping("/tree/{roleId}")
    @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "Long")
    @ApiOperation(value = "返回角色的菜单集合", notes = "sys_menu_tree_role")
    @PreAuthorize("@pms.hasPermission('sys_menu_tree_role')")
    public R<List<Long>> getRoleTree(@PathVariable Long roleId) {
        return R.ok(sysMenuService.findMenuByRoleId(roleId).stream().map(AdminMenuVO::getMenuId).collect(Collectors.toList()));
    }

    /**
     * 通过ID查询菜单的详细信息
     *
     * @param id 菜单ID
     * @return 菜单详细信息
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询菜单的详细信息", notes = "sys_menu_info")
    @ApiImplicitParam(name = "id", value = "菜单ID", required = true, dataType = "Long")
    @PreAuthorize("@pms.hasPermission('sys_menu_info')")
    public R<AdminMenuVO> getById(@PathVariable Long id) {
        return R.ok(sysMenuService.getObjXq(id));
    }

    /**
     * 新增菜单
     *
     * @param obj 菜单信息
     * @return success/false
     */
    @SysLog("新增菜单")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('sys_menu_add')")
    @ApiOperation(value = "新增菜单", notes = "sys_menu_add")
    public R<Boolean> save(@Valid @RequestBody AdminSysMenuAddDto obj) {
        return R.ok(sysMenuService.saveAdminObj(obj));
    }

    /**
     * 删除菜单
     *
     * @param id 菜单ID
     * @return success/false
     */
    @SysLog("删除菜单")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('sys_menu_del')")
    @ApiImplicitParam(name = "id", value = "菜单ID", required = true, dataType = "Integer")
    @ApiOperation(value = "删除菜单", notes = "sys_menu_del")
    public R<Boolean> removeById(@PathVariable Long id) {
        return R.ok(sysMenuService.removeMenuById(id));
    }

    /**
     * 更新菜单
     *
     * @param obj
     * @return
     */
    @SysLog("更新菜单")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('sys_menu_edit')")
    @ApiOperation(value = "更新菜单", notes = "sys_menu_edit")
    public R<Boolean> update(@Valid @RequestBody AdminSysMenuEditDto obj) {
        return R.ok(sysMenuService.editAdminObj(obj));
    }

}
